package com.team.cloudsharing.service.mail;

import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import com.team.cloudsharing.dao.folder.FolderDAO;
import com.team.cloudsharing.dao.folder.FolderDO;
import com.team.cloudsharing.dao.user.UserDAO;
import com.team.cloudsharing.dao.user.UserDO;
import com.team.cloudsharing.service.folder.FolderServiceImpl;

import freemarker.template.Configuration;

@Service("mailService")
public class MailServiceImpl implements MailService{
	
	final static Logger logger = Logger.getLogger(FolderServiceImpl.class);
	
	@Autowired
	UserDAO userDAO;
	
	@Autowired
	FolderDAO folderDAO;
	
	@Autowired
	JavaMailSender mailSender;

	@Autowired
	Configuration freemarkerConfiguration;

	@Value("${EMAIL_SENDER}")
	String senderEmail;
	
	@Value("${EMAIL_SENDER_NAME}")
	String senderName;
	
	@Value("${HOMEPAGE_URL}")
	String homepageUrl;
	
	@Override
	public void sendMailActivateAccount(final String userEmail) {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
				
				UserDO userDO = userDAO.findUserByUserEmail(userEmail);
				
				if (userDO != null){
					StringBuilder activationLink = new StringBuilder();
					activationLink.append(homepageUrl);
					activationLink.append("user/registerConfirm?userEmail=");
					activationLink.append(userEmail);
					activationLink.append("&activationCode=");
					activationLink.append(userDO.getActivationCode());
					
					message.setFrom(senderEmail, senderName);
					message.setTo(userEmail);
					message.setSubject("[CloudSharing] Activation Email");
	
					Map<String, Object> data = new HashMap<String, Object>();
					data.put("homepageUrl", homepageUrl);
					data.put("username", userDO.getUserName());
					data.put("activationLink", activationLink.toString());
					data.put("emailPreheader", "Activation Email");
					data.put("msg", "Thanks for signing up to CloudSharing - We're excited to have you on board! To storage your first file, please verify your email address by clicking the button below.");
					
					String plainText = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("activateAccountText.ftl"), data);
					String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("activateAccountHtml.ftl"), data);
					message.setText(plainText, htmlText);
				}
				else{
					return;
				}
			}
		};
		ThreadSendMail thread = new ThreadSendMail(preparator);
		thread.start();
	}

	@Override
	public void sendMailForgotPassword(final String userEmail) {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
				
				UserDO userDO = userDAO.findUserByUserEmail(userEmail);
				StringBuilder linkSetNewPassword = new StringBuilder();
				linkSetNewPassword.append(homepageUrl);
				linkSetNewPassword.append("user/resetPassword?key=");
				linkSetNewPassword.append(userDO.getUserId());
				linkSetNewPassword.append('@');
				linkSetNewPassword.append(userDO.getPassword());
				
				message.setFrom(senderEmail, senderName);
				message.setTo(userEmail);
				message.setSubject("[CloudSharing] Forgot Password Email");

				Map<String, Object> data = new HashMap<String, Object>();
				data.put("homepageUrl", homepageUrl);
				data.put("username", userDO.getUserName());
				data.put("linkSetNewPassword", linkSetNewPassword.toString());
				data.put("emailPreheader", "Forgot Password Email");
				data.put("msg", "Someone recently requested a password change for your CloudSharing account. If this was you, you can set a new password");
				
				String plainText = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("forgotPasswordText.ftl"), data);
				String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("forgotPasswordHtml.ftl"), data);
				message.setText(plainText, htmlText);
			}
		};
		ThreadSendMail thread = new ThreadSendMail(preparator);
		thread.start();
	}

	@Override
	public void sendMailShareFolder(final String userEmailReceive, final long folderId, final String userEmailShare) {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
				
				UserDO userDOReceive = userDAO.findUserByUserEmail(userEmailReceive);
				UserDO userDOShare = userDAO.findUserByUserEmail(userEmailShare);
				FolderDO folderDO = folderDAO.findFolderById(folderId);
				StringBuilder linkCloudSharing = new StringBuilder();
				linkCloudSharing.append(homepageUrl);
				linkCloudSharing.append("sharing");
				
				if (userDOReceive != null && folderDO != null){
					message.setFrom(senderEmail, senderName);
					message.setTo(userEmailReceive);
					message.setSubject("[CloudSharing] Share folder");
	
					Map<String, Object> data = new HashMap<String, Object>();
					data.put("homepageUrl", homepageUrl);
					data.put("username", userDOReceive.getUserName());
					data.put("nameFolderShare", folderDO.getFolderName());
					data.put("userShare", userDOShare.getUserName());
					data.put("linkCloudSharing", linkCloudSharing.toString());
					data.put("emailPreheader", "Share folder");
					
					String plainText = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("shareFolderText.ftl"), data);
					String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("shareFolderHtml.ftl"), data);
					message.setText(plainText, htmlText);
				}
				else{
					return;
				}
			}
		};
		ThreadSendMail thread = new ThreadSendMail(preparator);
		thread.start();
	}
	@Override
	public void sendLinkToEmail(final String userEmail, final String documentUrl,
			final String userEmailShare) {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
				
				String[] listUserEmailShared = userEmailShare.split("-|\\,|\\;");
				
				UserDO userDO = userDAO.findUserByUserEmail(userEmail);
				
				for(int i = 0; i < listUserEmailShared.length; i++){
					message.setFrom(senderEmail, senderName);
					message.setTo(listUserEmailShared[i]);
					message.setSubject("[CloudSharing] Share Document");
	
					Map<String, Object> data = new HashMap<String, Object>();
					data.put("homepageUrl", homepageUrl);
					data.put("username", "Sir/Madam");
					data.put("userShare", userDO.getUserName());
					data.put("linkCloudSharing", documentUrl);
					data.put("emailPreheader", "Share document");
					
					String plainText = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("shareLinkText.ftl"), data);
					String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("shareLinkHtml.ftl"), data);
					message.setText(plainText, htmlText);
				}
			}
		};
		ThreadSendMail thread = new ThreadSendMail(preparator);
		thread.start();
	}
	class ThreadSendMail extends Thread{
		MimeMessagePreparator preparator;
		
		public ThreadSendMail(MimeMessagePreparator preparator) {
			this.preparator = preparator;
		}
		@Override
		public void run() {
			mailSender.send(preparator);
		}
	}
}
